<?php
set_time_limit(0);
function do_action($data_file_path)
{
    if (!file_exists($data_file_path))
    {
        echo '数据文件不存在';
        exit();
    }
    $data_del_media = $data_index = array();
    // 逐行读取数据
    $data_file = fopen($data_file_path, 'r');
    $locked = flock($data_file, LOCK_EX + LOCK_NB);
    while (!feof($data_file))
    {
        $data_item = fgets($data_file);
        $data_item = (is_string($data_item) && strlen($data_item)>0) ? trim($data_item) : '';
        if (strlen($data_item) <1)
        {
            continue;
        }
        $data_item = preg_replace("/\r\n/", '', rtrim($data_item));
        $data_item_arr = explode('""","""', $data_item);
        $name = trim($data_item_arr[0]);
        $content_id = trim($data_item_arr[1]);
        $media_id = trim($data_item_arr[2]);
        $index_id = trim($data_item_arr[3]);
        if(strlen($content_id) != 20 || strlen($media_id) != 32 || strlen($index_id) != 32)
        {
            continue;
        }
        $str_temp = substr($content_id, 0,8);
        if($str_temp == 'JSB12031' && !in_array($index_id, $data_index))
        {
            $data_index[] = $index_id;
        }
        else if(in_array($index_id, $data_index))
        {
            $data_del_media[] = array(
                'm_id'=>$media_id,
                'i_id'=>$index_id,
                'c_id'=>$content_id,
                'name'=>$name,
            );
        }
    }
    flock($data_file, LOCK_EX + LOCK_NB);
    fclose($data_file);
    if(!is_array($data_del_media) || empty($data_del_media))
    {
        echo "no_data";die;
    }
    export_csv($data_del_media);
}
function export_csv($data)
{
    $header = array (
        '片源ID',
        '分集ID',
        'CID',
        '名称'        
    );
    $filename=date('Ymd_His').'_del_media.csv';
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=". $filename);
    header('Cache-Control: max-age=0');
    print(chr(0xEF).chr(0xBB).chr(0xBF));
	ob_start();
    $fp = fopen('php://output', 'a');
    if(!empty($header))
    {
        fputcsv($fp, $header);
    }
    foreach ($data as $_v)
    {
        fputcsv($fp, array_values($_v));
    }
    unset($fp);
    unset($data);
    ob_flush();
    flush();
    return ;
}
$file=dirname(__FILE__)."/test.txt";
do_action($file);